<?php

namespace MoChat\App\Statistic\Action\Client;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 客户统计
 * @Controller
 */
class ClientTotal extends AbstractAction
{

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticClient/total", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $data['startTime'] = $data['startTime'] ?? date('Y-m-d 00:00:00');
        $data['endTime'] = $data['endTime'] ?? date('Y-m-d H:i:s');
        //客户总数
        $clientTotal = Db::table('client')
          ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('work_employee_id', $data['employeeId']);
            })->count();
        //客户新增
        $newClientTotal = Db::table('client')
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('created_at', [$data['startTime'], $data['endTime']]);
            })->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('work_employee_id', $data['employeeId']);
            })->count();

        //客户跟进
        $clientFollowUpNumber = Db::table('client')
            ->join('client_follow_record as record','record.client_id','=','client.id')
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('record.created_at', [$data['startTime'], $data['endTime']]);
            })->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('client.work_employee_id', $data['employeeId']);
            })->count(Db::raw('DISTINCT mc_record.client_id'));
        return [
            'clientTotal' => $clientTotal,//客户总数
            'newClientTotal' => $newClientTotal,//客户新增
            'clientFollowUpNumber' => $clientFollowUpNumber,//客户跟进
        ];
    }
}
